package com.andersonlfeitosa.encryptor;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import com.andersonlfeitosa.encryptor.constants.Operation;
import com.andersonlfeitosa.encryptor.exceptions.OperationNotFoundException;

public class Main {

	public static void main(String[] args) {
		
		if (args.length == 2) {
			try {
				Operation op = Operation.createOperation(args[0]);
				System.out.println(op.execute(args[1]));
				System.exit(0);
			} catch (OperationNotFoundException e) {
				printErrorMessage(e);
			} catch (InvalidKeyException e) {
				printErrorMessage(e);
			} catch (NoSuchAlgorithmException e) {
				printErrorMessage(e);
			} catch (NoSuchPaddingException e) {
				printErrorMessage(e);
			} catch (IllegalBlockSizeException e) {
				printErrorMessage(e);
			} catch (BadPaddingException e) {
				printErrorMessage(e);
			}
		} else {
			printErrorMessage();
		}
	}

	private static void printErrorMessage() {
		printErrorMessage(null);
	}

	private static void printErrorMessage(Exception e) {
		StringBuilder sb = new StringBuilder();
		
		if (e != null) {
			sb.append(e.getMessage());
			sb.append("\n");
		}
		
		sb.append("Usage: java -jar encryptor.jar operation parameter");
		sb.append("\n");
		sb.append("Operations: encode | decode");
		sb.append("\n");
		sb.append("Parameter: text or hash to encode or decode");
		
		System.err.println(sb.toString());
		System.exit(1);
	}
}